// yijing.js
const lunar = require('./lunar')

// 卦象定义
const HEXAGRAMS = {
  QIAN: {
    name: '乾',
    nature: '天',
    attribute: '刚健',
    meaning: '乾为天，刚健中正，自强不息。',
    lines: [
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 }
    ]
  },
  KUN: {
    name: '坤',
    nature: '地',
    attribute: '柔顺',
    meaning: '坤为地，厚德载物，包容万物。',
    lines: [
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 }
    ]
  },
  ZHEN: {
    name: '震',
    nature: '雷',
    attribute: '动',
    meaning: '震为雷，动而向上，充满活力。',
    lines: [
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 }
    ]
  },
  KAN: {
    name: '坎',
    nature: '水',
    attribute: '险',
    meaning: '坎为水，险中有机，智慧灵动。',
    lines: [
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 }
    ]
  },
  GEN: {
    name: '艮',
    nature: '山',
    attribute: '止',
    meaning: '艮为山，稳重如山，适可而止。',
    lines: [
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 }
    ]
  },
  XUN: {
    name: '巽',
    nature: '风',
    attribute: '入',
    meaning: '巽为风，谦逊顺从，循序渐进。',
    lines: [
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 },
      { type: 'yin', value: 6 }
    ]
  },
  LI: {
    name: '离',
    nature: '火',
    attribute: '丽',
    meaning: '离为火，光明照耀，文明向上。',
    lines: [
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 }
    ]
  },
  DUI: {
    name: '兑',
    nature: '泽',
    attribute: '悦',
    meaning: '兑为泽，喜悦和乐，和谐美满。',
    lines: [
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 },
      { type: 'yang', value: 9 },
      { type: 'yin', value: 6 }
    ]
  }
}

// 易经计算器类
class YijingCalculator {
  constructor() {
    this.lunar = lunar
  }

  // 计算卦象
  calculate({ birthDate, birthTime, question }) {
    try {
      // 获取农历日期
      const [year, month, day] = birthDate.split('-').map(Number)
      const lunarDate = this.lunar.solarToLunar(year, month, day)
      
      // 生成本卦
      const hexagram = this.generateHexagram(lunarDate, birthTime, question)
      
      // 生成变卦
      const changedHexagram = this.generateChangedHexagram(hexagram, question)
      
      return {
        hexagram,
        changedHexagram,
        interpretation: this.getInterpretation(hexagram, changedHexagram, question)
      }
    } catch (error) {
      console.error('易经计算出错：', error)
      throw error
    }
  }

  // 生成本卦
  generateHexagram(lunarDate, birthTime, question) {
    try {
      // 使用问题字符串的哈希值作为随机种子
      const seed = this.hashString(question)
      const dayNum = lunarDate.day
      const monthNum = lunarDate.month
      const hourNum = parseInt(birthTime.split(':')[0])
      
      // 根据日期、时间和问题生成卦象
      const hexagramKeys = Object.keys(HEXAGRAMS)
      const index = (dayNum + monthNum + hourNum + seed) % hexagramKeys.length
      return HEXAGRAMS[hexagramKeys[index]]
    } catch (error) {
      console.error('生成本卦出错：', error)
      throw error
    }
  }

  // 生成变卦
  generateChangedHexagram(hexagram, question) {
    try {
      // 使用问题字符串的哈希值确定变爻位置
      const seed = this.hashString(question)
      const changedLines = [...hexagram.lines]
      const changeIndex = seed % 6
      
      // 改变对应位置的爻
      changedLines[changeIndex] = {
        type: changedLines[changeIndex].type === 'yang' ? 'yin' : 'yang',
        value: changedLines[changeIndex].type === 'yang' ? 6 : 9
      }
      
      // 查找对应的变卦
      const changedHexagram = this.findHexagramByLines(changedLines)
      return changedHexagram || hexagram
    } catch (error) {
      console.error('生成变卦出错：', error)
      throw error
    }
  }

  // 根据爻线查找卦象
  findHexagramByLines(lines) {
    return Object.values(HEXAGRAMS).find(hexagram => 
      hexagram.lines.every((line, index) => 
        line.type === lines[index].type
      )
    )
  }

  // 简单的字符串哈希函数
  hashString(str) {
    let hash = 0
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash
    }
    return Math.abs(hash)
  }

  // 获取卦象解读
  getInterpretation(hexagram, changedHexagram, question) {
    try {
      return {
        general: `当前卦象为${hexagram.name}卦，${hexagram.meaning}`,
        detail: this.getDetailedInterpretation(hexagram, changedHexagram, question),
        advice: this.getAdvice(hexagram, changedHexagram, question)
      }
    } catch (error) {
      console.error('获取卦象解读出错：', error)
      throw error
    }
  }

  // 获取详细解读
  getDetailedInterpretation(hexagram, changedHexagram, question) {
    try {
      let detail = `从${hexagram.nature}的角度来看，${hexagram.meaning}。`
      
      if (changedHexagram && changedHexagram !== hexagram) {
        detail += `\n变卦为${changedHexagram.name}卦，${changedHexagram.meaning}。`
      }
      
      detail += `\n对于您的问题"${question}"，建议您${this.getAdvice(hexagram, changedHexagram, question)}。`
      
      return detail
    } catch (error) {
      console.error('获取详细解读出错：', error)
      throw error
    }
  }

  // 获取建议
  getAdvice(hexagram, changedHexagram, question) {
    try {
      const adviceMap = {
        '乾': '保持积极进取的态度，勇于面对挑战。',
        '坤': '以包容和耐心的心态处理问题。',
        '震': '把握机会，果断行动。',
        '坎': '谨慎行事，化险为夷。',
        '艮': '适可而止，不要过分追求。',
        '巽': '循序渐进，保持谦逊。',
        '离': '保持光明正大的态度。',
        '兑': '以愉悦的心态面对问题。'
      }
      
      let advice = adviceMap[hexagram.name] || '保持平和的心态，顺其自然。'
      
      if (changedHexagram && changedHexagram !== hexagram) {
        advice += `\n同时要注意${adviceMap[changedHexagram.name] || '保持平和的心态，顺其自然。'}`
      }
      
      return advice
    } catch (error) {
      console.error('获取建议出错：', error)
      throw error
    }
  }
}

// 导出模块
module.exports = new YijingCalculator() 